package com.luozhili.rabbitmqlearningdemo.base_demo;

import com.rabbitmq.client.*;

import java.io.IOException;

public class Recv2 {
    private final static String QUEUE_NAME = "learn_queue_1";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.31.226");
        factory.setUsername("zhangsan");
        factory.setPassword("123456");
        factory.setVirtualHost("/shopping");

        //拿到 连接 从连接中拿到 通道
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");


        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,
                                       byte[] body) throws IOException {
                String message = new String(body);
                System.out.println(" [x] Received '" + message + "'");
                //手动进行ack
                //第二个参数是否同时确认多个消息
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
        //等待新消息，不关闭  ， false 设置手动 ACK
        channel.basicConsume(QUEUE_NAME, false, consumer);

    }
}
